package com.motorhome.manage.controller;

import com.motorhome.base.util.Result;
import com.motorhome.manage.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: John
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String toLogin() {
        return "login/login";
    }

    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        String loginName = request.getParameter("username");
        String loginPass = request.getParameter("password");
        String code = request.getParameter("code");
        Result result = loginService.doLogin(request, response, loginName, loginPass, code);
        if (result.getRet() == 0) {
            return "redirect:/manage/main/index";
        } else {
            redirectAttributes.addFlashAttribute("result", result);
            return "redirect:/manage/login/toLogin";
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        loginService.logout(request, response);
        return "login/login";
    }

}
